// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#include "NodeCast.h"
#include "Rules/Rule.h"

#include "Rules/LetAsPatternMatchRule.h"

using namespace Cangjie::AST;

namespace CangjieMigrator::Rules {

LetAsPatternMatchRule::LetAsPatternMatchRule() {}

MatchRule::Type LetAsPatternMatchRule::GetType() const
{
    return Type::LetAsPattern;
}

std::unique_ptr<ExtractedInfo> LetAsPatternMatchRule::ExtractInfo(const Node &node, PositionRange range)
{
    if (node.astKind != ASTKind::LET_PATTERN_DESTRUCTOR) {
        return nullptr;
    }
    const auto &letPattern = Cast<ASTKind::LET_PATTERN_DESTRUCTOR>(node);

    if (!letPattern.initializer) {
        return nullptr;
    }
    const auto &initializer = *letPattern.initializer;

    if (initializer.astKind != ASTKind::AS_EXPR) {
        return nullptr;
    }
    const auto &asExpr = Cast<ASTKind::AS_EXPR>(initializer);
    return std::make_unique<LetAsPatternExtractedInfo>(PositionRange(asExpr), letPattern);
}

bool LetAsPatternMatchRule::MatchConditions(const ExtractedInfo *info)
{
    const auto i = dynamic_cast<const LetAsPatternExtractedInfo *>(info);
    if (!i) {
        return false;
    }
    return true;
}

std::vector<Actions::Action> LetAsPatternMatchRule::GenerateAction(
    UpdateInstance::File &file, const ExtractedInfo &info, const std::string &update, const Rule *rule) const
{
    const auto i = dynamic_cast<const LetAsPatternExtractedInfo &>(info);
    const auto result = "(" + file.GetContentInRange(i.replacePosition) + ")";
    return {Actions::Replace(i.replacePosition, result, rule)};
}

std::unique_ptr<MatchRule> LetAsPatternMatchRule::TryBuild(const TomlConfig &config)
{
    if (config.title != "LetAsPattern") {
        return nullptr;
    }
    return std::make_unique<LetAsPatternMatchRule>();
}

} // namespace CangjieMigrator::Rules
